﻿/// <reference path="../../js/utils.js" />
'use strict';

define([
    'screenView',
    'commonModels',

    'backgrid.all',

    'screens/products/products.model',

    'backbone.modelbinder',
],
function (
    ScreenView,
    CommonModels,
    Backgrid,
    ProductsModel
) {
    var View = ScreenView.extend({
        super: null,

        name: 'products',
        title: 'Productos',

        //catalogCollSource: App.products,
        catalogCollFn: CommonModels.ProductColl,
        catalogColl: null,
        catalogDefault: null,
        catalogGrid: null,
        catalogModelFn: CommonModels.ProductModel,
        catalogName: 'Product',

        events: function() {
            return {
                //'click #saveBtn': '_saveBtn_click',
                
                'click #adjustPriceBtn': 'adjustPriceBtn_click',
                'click #priceAdjProfitBtn': 'priceAdjProfitBtn_click',
                'click #priceAdjTotalBtn': 'priceAdjTotalBtn_click',
                'click #resetPriceBtn': 'resetPriceBtn_click',
            };
        },

        constructor: function () {
            this.super = View.__super__;

            //this.catalogColl = this.catalogCollSource.clone();
            this.catalogColl = new this.catalogCollFn();

            this.catalogDefault = new this.catalogModelFn();

            this.modelBinder = new Backbone.ModelBinder();

            return this.super.constructor.apply(this, arguments);
        },

        adjustPrice: function (type) {
            this.catalogGrid.columns.each(function (model, i) {
                model.set('editable', false)
            });

            this.model.set({
                priceAdjusted: true,
                priceAdjType: type,
            });
        },
        delegateModelEvents: function () {
            this.listenTo(this.catalogColl, 'add', this._catalogColl_add, this)
                .listenTo(this.catalogColl, 'change', this._catalogColl_change, this)
                .listenTo(this.model, 'change:priceAdjusted change:priceAdjType', this._model_change_priceAdjusted_priceAdjType, this);
                //.listenTo(this.catalogColl, 'add change remove', this._catalogColl_addChangeRemove, this);
            

            return this.super.delegateModelEvents.apply(this, arguments);
        },
        render: function () {
            this.super.render.apply(this);

            var that = this;

            /* First render actions. */
            if (!this.rendered) {
                this.catalogGrid = new Backgrid.Grid({
                    columns: [
                        {
                            name: 'code',
                            label: 'Código',
                            cell: 'string-center',
                        },
                        {
                            name: 'name',
                            label: 'Nombre',
                            cell: 'string-center',
                        },
                        {
                            name: 'price',
                            label: 'Precio',
                            cell: Backgrid.NumberCell.extend({
                                super: null,
                                screenViewModel: this.model,

                                formatter: new PriceCellFormater(),

                                constructor: function () {
                                    this.super = Backgrid.NumberCell.__super__;

                                    this.listenTo(this.screenViewModel, 'change:priceAdjusted', this._screenViewModel_change_priceAdjusted, this);

                                    this.formatter.screenViewModel = this.screenViewModel;

                                    this.super.constructor.apply(this, arguments);
                                },

                                _screenViewModel_change_priceAdjusted: function (model, options) {
                                    var priceAdj = this.screenViewModel.get('priceAdjusted');

                                    if (priceAdj == true) {
                                        if (this.$el.hasClass('priceAdjustedCell') == false)
                                            this.$el.addClass('priceAdjustedCell');
                                    }
                                    else {
                                        this.$el.removeClass('priceAdjustedCell');
                                    }
                                },
                            }),
                        },
                        {
                            name: 'dimensions',
                            label: 'Dimensiones',
                            cell: 'string-center',
                        },
                        {
                            name: 'description',
                            label: 'Descripción',
                            cell: 'string-left',
                        },
                        {
                            name: 'active',
                            label: 'Activo',
                            cell: 'boolean',
                        },
                    ],
                    collection: this.catalogColl,
                });
                this.catalogGrid.render();
                // Render the grid and attach the Grid's root to your HTML document
                this.$el.find('#catalog').append(this.catalogGrid.el);


                this.modelBinder.bind(
                    this.model,
                    this.el,
                    utils.misc.getModelBindingsFromDOM(
                        this.el,
                        {
                            priceAdjPercentage: [
                                {
                                    selector: '#priceAdjProfitBtn, #priceAdjTotalBtn',
                                    elAttribute: 'disabled',
                                    converter: function (direction, value) {
                                        var valueFix = parseFloat(value);
                                        return (isNaN(valueFix) || value == 0);
                                    },
                                },
                            ],
                            priceAdjusted: [
                                {
                                    selector: '#adjustPriceBtn, #resetPriceBtn',
                                    elAttribute: 'disabled',
                                    converter: function (direction, value) {
                                        return !value;
                                    },
                                },
                            ],
                        }
                    )
                );


                /* Indicates that the view was rendered at least one time. */
                this.rendered = true;
            }
            /* Not first render actions. */
            else {
                
            }


            return this;
        },
        resetPriceAdjustment: function () {
            this.catalogGrid.columns.each(function (model, i) {
                model.set('editable', true)
            });

            this.model.set({
                priceAdjusted: false,
            });
        },
        show: function (data) {
            this.catalogColl.fetch({ success: _.bind(this._catalogColl_fetch_success, this) });

            return this.super.show.apply(this, arguments);
        },

        //_catalogColl_addChangeRemove: function (model, coll, options) {
        //    try {
        //        this.model.set('changed', true);

        //        this.catalogColl.push(new this.catalogModelFn());
        //    }
        //    catch (Error) { console.error(Error); }
        //},
        _catalogColl_add: function (model, coll, options) {
            try {
                if (!this.catalogColl.findWhere(this.catalogDefault.toJSON()))
                    this.catalogColl.add(new this.catalogModelFn());
            }
            catch (Error) { console.error(Error); }
        },
        _catalogColl_change: function (model, coll, options) {
            try {
                var id = model.get('id');

                if (id != 0) {
                    App.billingService.updateCatalogItem(
                        {
                            CatalogName: this.catalogName,
                            Keys: {
                                Id: model.get('id'),
                            },
                            Properties: model.changed,
                        },
                        {
                            success: function (resp) {
                                if (resp.Success == true) {
                                    console.debug(resp);
                                }
                            },
                            error: function () {
                                console.debug("error");
                            },
                        }
                    );
                }
                else {
                    App.billingService.addCatalogItem(
                        {
                            CatalogName: this.catalogName,
                            Properties: model.changed,
                        },
                        {
                            success: function (resp) {
                                if (resp.Success == true) {
                                    //Set model id.
                                    model.set({ id: resp.Data, }, { silent: true, });
                                }
                            },
                            error: function () {
                                console.debug("error");
                            },
                        }
                    );
                }


                if (!this.catalogColl.findWhere(this.catalogDefault.toJSON()))
                    this.catalogColl.add(new this.catalogModelFn());
            }
            catch (Error) { console.error(Error); }
        },
        _catalogColl_fetch_success: function (coll) {
            try {
                if (coll.length == 0)
                    this.catalogColl.add(new this.catalogModelFn());
            }
            catch (Error) { console.error(Error); }
        },
        //_model_change_priceAdjProfitIndex: function (model, options) {
        //    var prop = 'priceAdjProfitIndex';

        //    this.adjustPriceByProfit(this.model.get(prop));
        //},
        adjustPriceBtn_click: function (e) {
            try {
                var that = this;

                App.billingService.adjustProductsPrice(
                    this.model.get('priceAdjIndex'),
                    {
                        success: function (resp) {
                            try {
                                if (resp.Success == true) {
                                    that.resetPriceAdjustment();

                                    that.catalogColl.fetch({ success: _.bind(that._catalogColl_fetch_success, that) });
                                }
                                else {
                                    console.debug(resp.Message);
                                }
                            }
                            catch (Error) {
                                console.error(Error);
                            }
                        },
                        error: function () {
                            console.debug("error");
                        },
                    }
                );
            }
            catch (Error) { console.error(Error); }
        },
        _model_change_priceAdjusted_priceAdjType: function (model, options) {
            try {
                this.catalogGrid.render();
            }
            catch (Error) { console.error(Error); }
        },
        priceAdjProfitBtn_click: function (e) {
            try {
                this.adjustPrice(ProductsModel.prototype.priceAdjustTypes.profit);
            }
            catch (Error) { console.error(Error); }
        },
        priceAdjTotalBtn_click: function (e) {
            try {
                this.adjustPrice(ProductsModel.prototype.priceAdjustTypes.total);
            }
            catch (Error) { console.error(Error); }
        },
        resetPriceBtn_click: function (e) {
            try {
                this.resetPriceAdjustment();
            }
            catch (Error) { console.error(Error); }
        },
        //_saveBtn_click: function (e) {
        //    try {
        //        this.model.set('changed', false);
        //    }
        //    catch (Error) { console.error(Error); }
        //},
    });

    var PriceCellFormater = function (options) {
        _.extend(this, this.defaults, options || {});

        this.numberFormatter = new Backgrid.NumberFormatter();
    };
    PriceCellFormater.prototype = new Backgrid.NumberFormatter();
    _.extend(PriceCellFormater.prototype, {
        numberFormatter: null,
        screenViewModel: null,

        fromRaw: function (number, model) {
            return this.numberFormatter.fromRaw(
                (this.screenViewModel.get('priceAdjusted') == false)
                    ? number
                    : number * this.screenViewModel.get('priceAdjIndex'),
                model
            );
        },
    });

    //var PriceCell = ;

    return View;
});